package com.max.rabbitmq.learn.retry;

import com.max.rabbitmq.learn.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

/**
 * @description TODO
 * @author yandong
 * @create 2021年4月06日 16:46:57
 */
public class Send {

    private static final String NORMAL = "max.normal";
    private static final String RETRY = "max.retry";
    private static final String FAIL = "max.fail";

    private static final String EXCHANGE_NORMAL = "exchange.max.normal";
    private static final String EXCHANGE_RETRY = "exchange.max.retry";
    private static final String EXCHANGE_FAIL = "exchange.max.fail";
    private static final String ROUTING_KEY = "test";

    public static void main(String[] args) throws IOException, TimeoutException {

        //获取连接
        Connection connection = ConnectionUtil.getConnection();
        //获取chanel chanel是操作rabbitmq broker的接口，即操作amqp协议的对象
        Channel channel = connection.createChannel();

        //声明正常队列
        Map normalArgs = new HashMap();
        //声明重试队列
        Map retryArgs = new HashMap();
        //声明死信队列
        Map failArgs = new HashMap();

        normalArgs.put("x-dead-letter-exchange", EXCHANGE_FAIL);

        retryArgs.put("x-dead-letter-exchange", EXCHANGE_NORMAL);
        retryArgs.put("x-message-ttl", 60 * 1000);

        channel.exchangeDeclare(EXCHANGE_NORMAL, BuiltinExchangeType.TOPIC, true);
        channel.exchangeDeclare(EXCHANGE_RETRY, BuiltinExchangeType.TOPIC, true);
        channel.exchangeDeclare(EXCHANGE_FAIL, BuiltinExchangeType.TOPIC, true);

        //正常队列
        channel.queueDeclare(NORMAL, true, false, false, normalArgs);
        //重试队列
        channel.queueDeclare(RETRY, true, false, false, retryArgs);
        //死信队列
        channel.queueDeclare(FAIL, true, false, false, failArgs);

        channel.queueBind(NORMAL, EXCHANGE_NORMAL, "#");
        channel.queueBind(RETRY, EXCHANGE_RETRY, "#");
        channel.queueBind(FAIL, EXCHANGE_FAIL, "#");

        //发送信息
        String message = "测试重试";
        /**
         * 0.交换机名称
         * 1.路由key(如果是直连则为队列的名称)
         * 2.message的额外属性
         * 3.message的消息体
         * */

        channel.basicPublish(EXCHANGE_NORMAL, ROUTING_KEY, new AMQP.BasicProperties().builder().messageId(UUID.randomUUID().toString()).build(), message.getBytes(StandardCharsets.UTF_8));
        channel.close();
        connection.close();
    }
}
